package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.entity.Student;
import com.example.haoqisystem.request.CreateStudentRequest;
import com.example.haoqisystem.request.QueryStudentListRequest;
import com.example.haoqisystem.request.UpdateStudentRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.respository.StudentRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
public class StudentService {

    private final StudentRepository studentRepository;

    //验证密码
    public boolean isPassword(String pwd){
        String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d).{8,16}$";
        return pwd.matches(regex);
    }

    //验证邮箱格式
    public boolean isEmail(String email){
        String regex="^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";
        return email.matches(regex);
    }

    //验证手机号
    public boolean isValidPhoneNumber(String phoneNumber) {
        // 移除号码中的空格、括号、破折号等特殊字符
        String cleanedNumber = phoneNumber.replaceAll("[\\s()-]+", "");

        // 验证手机号格式
        String regex = "^(\\+?\\d{1,3})?[-.\\s]?\\(?\\d{1,4}\\)?[-.\\s]?\\d{1,4}[-.\\s]?\\d{1,9}$";
        return cleanedNumber.matches(regex);
    }

    public BaseResponse<Student> register(CreateStudentRequest request) {
        if(!isEmail(request.getEmail())){
            return new BaseResponse<>("邮箱格式错误！",false,null);
        }
        if(!isPassword(request.getPassword())){
            return new BaseResponse<>("密码格式错误！",false,null);
        }
        try{
            Optional<Student> studentOptional=studentRepository.findByAccountAndDeletedFalse(request.getAccount());
            if(studentOptional.isPresent()){
                return new BaseResponse<>("该账户已存在！",false,null);
            }
            Student student=new Student();
            BeanUtil.copyProperties(request,student, CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,studentRepository.save(student));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //登录
    public BaseResponse<Student> login(String account, String password) {
        try{
            Optional<Student> studentOptional=studentRepository.findByAccountAndDeletedFalse(account);
            if(!studentOptional.isPresent()){
                return new BaseResponse<>("该账户不存在！",false,null);
            }
            Student student=studentOptional.get();
            if(!password.equals(student.getPassword())){
                return new BaseResponse<>("密码错误！",false,null);
            }
            return new BaseResponse<>("登录成功！",true,student);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<List<Student>> queryList(QueryStudentListRequest request) {
        Specification<Student> specification=(root, query, builder) -> {
            List<Predicate> predicates=new ArrayList<>();
            if(request.getName()!=null&&!request.getName().equals("")){
                String nameLike="%"+request.getName()+"%";
                predicates.add(builder.like(root.get("name"),nameLike));
            }
            if (request.getGender() != null) {
                predicates.add(builder.equal(root.get("gender"), request.getGender()));
            }
            if (request.getCompanyName() != null && !request.getCompanyName().equals("")) {
                String companyNameLike = "%" + request.getCompanyName() + "%";
                predicates.add(builder.like(root.get("companyName"), companyNameLike));
            }
            if (request.getWorkPlace() != null && !request.getWorkPlace().equals("")) {
                String workPlaceLike = "%" + request.getWorkPlace() + "%";
                predicates.add(builder.like(root.get("workPlace"), workPlaceLike));
            }
            if (request.getTechnicalLevel() != null && !request.getTechnicalLevel().equals("")) {
                String technicalLevelLike = "%" + request.getTechnicalLevel() + "%";
                predicates.add(builder.like(root.get("technicalLevel"), technicalLevelLike));
            }
            predicates.add(builder.equal(root.get("deleted"),false));
            return builder.and(predicates.toArray(new Predicate[0]));
        };
        List<Student> list=studentRepository.findAll(specification);
        Collections.reverse(list);
        return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
    }

    public BaseResponse<Student> detail(Long id) {
        try{
            Optional<Student> studentOptional=studentRepository.findByIdAndDeletedFalse(id);
            if(!studentOptional.isPresent()){
                return new BaseResponse<>("该学生不存在！",false,null);
            }
            Student student=studentOptional.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,student);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<Student> update(UpdateStudentRequest request) {
        try{
            Optional<Student> studentOptional=studentRepository.findByIdAndDeletedFalse(request.getId());
            if(!studentOptional.isPresent()){
                return new BaseResponse<>("该学生不存在！",false,null);
            }
            Student student=studentOptional.get();
            BeanUtil.copyProperties(request,student,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,studentRepository.save(student));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    public BaseResponse<String> delete(Long id) {
        try{
            Optional<Student> studentOptional=studentRepository.findByIdAndDeletedFalse(id);
            if(!studentOptional.isPresent()){
                return new BaseResponse<>(ConstUtil.DELETED_FALSE,false,"该学员不存在！");
            }
            Student student=studentOptional.get();
            student.setDeleted(true);
            studentRepository.save(student);
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,null);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }
}
